const checkBox = require("../UI/checkBox");
const connection = require("../db/connection");
const input = require("scanline");
const changeCount = require("../functions/changeCount");

async function payQ() {
    return new Promise((result) => {
        connection.query("SELECT * FROM product", async function (error, products) {
            if (error) {
                console.log("查找全部商品信息失败!", error);
                process.exit(1);
            }

            if (products.length <= 0) {
                console.log("\033[31m商品信息为空\033[0m");
                process.exit(2);
            }

            const productsName = products.map((product) => product["名称"]);
            const select = await checkBox(productsName, "请勾选你要购买的商品(按下空格选择,按a全选,按回车确定你的选择):\n");

            let price = 0.0;
            let productList = [];
            for (let product of products) {
                for (let xz of select.selects) {
                    if (product["名称"] === xz) {
                        const num = parseInt(await input(`想要购买${product["名称"]}的数量:`));
                        if (num > product["数量"]) {
                            console.log("\033[31m该商品库存不足,请减少购买数量！\033[0m");
                            process.exit(1);
                        }
                        price += product["价格"] * num;
                        productList.push({
                            ...product,
                            "购买数量": num,
                            "花费价钱": product["价格"] * num
                        });
                    }
                }
            }
            console.log(`最终需支付的金额为:${price}￥`);

            if (
                (await input("\033[31m请您确认是否支付?[y确认/n取消]\033[0m")).toLowerCase() === "y"
            ) {
                console.log("********************************************");
                const today = new Date();
                const date = today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate();
                const time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
                console.log(date + " " + time);


                console.log("您购买了以下商品")
                for (let p of productList) {
                    console.log(`${p["名称"]}*${p["购买数量"]}:\t${p["花费价钱"]}￥`);
                }
                console.log(`您本次的消费总额为:${price}￥`);
                console.log("您的小票请收好，欢迎下次光临，祝您生活愉快！");
                result(productList);
            } else {
                console.log("\033[31m您取消了支付操作!\033[0m");
            }
            console.log("********************************************");
        });
    });
}

async function pay() {
    let productList = await payQ();
    console.log(productList);
    for (let p of productList) {
        changeCount(p["名称"], p["数量"] - p["购买数量"]);
    }
    connection.end();
}

module.exports = pay;